// 倒计时返回 天时分秒，需要传入完整的时间格式时分秒
const countDown = (time) => {
    let nowTime = +new Date() // 当前时间总的毫秒数
    let inputTime = +new Date(time) // 用户传入时间总的毫秒数
    let times = (inputTime - nowTime) / 1000 // 剩余时间总的毫秒数
    let d = parseInt(times / 60 / 60 / 24) // 天
    d = d < 10 ? '0' + d : d
    let h = parseInt(times / 60 / 60 % 24) // 时
    h = h < 10 ? '0' + h : h
    let m = parseInt(times / 60 % 60) // 分
    m = m < 10 ? '0' + m : m
    let s = parseInt(times % 60) // 秒
    s = s < 10 ? '0' + s : s
    return `${d}天${h}时${m}分${s}秒`
}

// 平滑滚动至顶部
const scrollToTop = () => {
    const c = document.documentElement.scrollTop || document.body.scrollTop;
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop)
        window.scrollTo(0, c - c / 8)
    }
}

// 深拷贝  新的newObj, 待拷贝值oldObj, console.log(newObj)
const deepCopy = (newObj, oldObj) => {
    for (let k in oldObj) {
        let item = oldObj[k]
        if (item instanceof Array) {
            newObj[k] = []
            deepCopy(newObj[k], item)
        } else if (item instanceof Object) {
            newObj[k] = {}
            deepCopy(newObj[k], item)
        } else {
            newObj[k] = item
        }
    }
}

// 验证手机号是否正确
const regTel = (tel) => {
    let reg = /^1[3|4|5|7|8]\d{9}$/
    return reg.test(tel)
}

// 生成指定范围的随机整数
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
// 生成指定范围的随机小数
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min

// 金钱格式化，三位加逗号
const formatMoney = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

// 毫秒转时间
const msToDate = (msec) => {
    let datetime = new Date(msec);
    let year = datetime.getFullYear();
    let month = datetime.getMonth();
    let date = datetime.getDate();
    let hour = datetime.getHours();
    let minute = datetime.getMinutes();
    let second = datetime.getSeconds();

    let result1 = year +
      '-' +
      ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
      '-' +
      ((date + 1) < 10 ? '0' + date : date) +
      ' ' +
      ((hour + 1) < 10 ? '0' + hour : hour) +
      ':' +
      ((minute + 1) < 10 ? '0' + minute : minute) +
      ':' +
      ((second + 1) < 10 ? '0' + second : second);

    let result2 = year +
      '-' +
      ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
      '-' +
      ((date + 1) < 10 ? '0' + date : date);

    return {
        hasTime: result1,
        withoutTime: result2
    };
}
export {
    countDown,
    scrollToTop,
    deepCopy,
    regTel,
    randomIntegerInRange,
    randomNumberInRange,
    formatMoney,
    msToDate
}
